package jp.co.worksap.ate.gomoku.rest;

import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.QueryParam;

import jp.co.worksap.ate.gomoku.hadoopai.EMRAI;
import jp.co.worksap.ate.gomoku.hadoopai.HadoopAI;
import jp.co.worksap.ate.gomoku.localai.MultiLevelAI;
import jp.co.worksap.ate.gomoku.model.GoPoint;
import jp.co.worksap.ate.gomoku.model.GoState;
import jp.co.worksap.ate.gomoku.model.Goban;
import jp.co.worksap.ate.gomoku.model.IGomokuAI;

import org.codehaus.jettison.json.JSONArray;
import org.codehaus.jettison.json.JSONException;


@Path("/nextmove")
public class GomokuResource {
	@GET
	@Path("/test")
	public String test() {
		return "[0,0]";
	}


	@GET
	@Path("/get")
	public String getNextMove(@QueryParam("x") int xSize,
			@QueryParam("y") int ySize, @QueryParam("black") String blackStr,
			@QueryParam("white") String whiteStr, @QueryParam("gotype") int goType,
			@QueryParam("aitype") int aiType, @QueryParam("ailevel") int aiLevel) throws JSONException {
		long beginTime = System.currentTimeMillis();
		Goban goban = new Goban(xSize, ySize);
		JSONArray blackArray = new JSONArray(blackStr);
		JSONArray whiteArray = new JSONArray(whiteStr);
		for(int i=0; i<blackArray.length(); i++) {
			int x = blackArray.getJSONArray(i).getInt(0);
			int y = blackArray.getJSONArray(i).getInt(1);
			goban.putBlack(x, y);
		}
		for(int i=0; i<whiteArray.length(); i++) {
			int x = whiteArray.getJSONArray(i).getInt(0);
			int y = whiteArray.getJSONArray(i).getInt(1);
			goban.putWhite(x, y);
		}
		if(xSize * ySize == blackArray.length() + whiteArray.length()) {
			return "[0,0]";
		}
		IGomokuAI aiService;
		if(aiType==1) {
			aiService = new MultiLevelAI();
		} else if(aiType==2) {
			aiService = new HadoopAI();
		} else {
			aiService = new EMRAI();
		}
		GoState selfType;
		if(goType<0) {
			selfType = GoState.BLACK;
		} else {
			selfType = GoState.WHITE;
		}
		GoPoint point = aiService.nextMove(goban, selfType, aiLevel);
		long endTime = System.currentTimeMillis();
		long time = endTime - beginTime;
		return "["+point.getX()+","+point.getY()+","+point.getNodeNum()+","+time+"]";
	}
}
